<?php

namespace app\api\controller;

use app\admin\model\Technician as TechnicianModel;
use ba\Random;
use ba\Tree;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Log;
use Throwable;
use think\facade\Db;
use think\facade\Config;
use app\common\controller\Frontend;
use app\common\library\token\TokenExpirationException;
use think\App;

/**
 * 技师数据
 */
class Technician extends Frontend
{
    protected array $noNeedLogin = ['*'];
    protected $model;

    protected array $noNeedPermission = ['recruit'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Technician;
    }

    //    public function index(): void
//    {
//        $rows = $this->model->field([
//            'technician_id',
//            'username',
//            'avatar',
//            'technician_name',
//            'is_service',
//            'is_travel',
//        ])->select();
//        $this->success("",$rows);
//    }

    /**
     * 技师列表
     * @return void
     */
    public function index()
    {
        $get = $this->request->get();
        $lng = $get['lng'] ?? "";
        $lat = $get['lat'] ?? "";
        $area_id = $get['area_id'] ?? "";
        $service_id = $get['service_id'] ?? null;

        $filed = ['lng', 'lat'];

        foreach ($filed as $value) {
            if (empty($get[$value])) {
                $this->error($value . '不能为空');
            }
        }
        $where = [];
        $where[] = ['status', '=', 1];//是否正常状态
        $where[] = ['area_id', '=', $area_id];//地区
        if (!empty($service_id)) {
            $technician_ids = Db::name('technician_service')->where('service_id', $get['service_id'])->column('technician_id');
            $where[] = ['technician_id', 'in', $technician_ids];
        }
        if (!empty($get['search'])) {
            $where[] = ['technician_name', 'like', "%{$get['search']}%"];
        }

        $ret = TechnicianModel::
            field("
     (6371 * ACOS(
        COS(RADIANS(lat)) * COS(RADIANS($lat)) * COS(RADIANS($lng) - RADIANS($lng)) +
        SIN(RADIANS(lat)) * SIN(RADIANS($lat))
    )) AS distance_km")->
            where($where)->
            withoutField('username,password,salt,person_imgs,ascription_id,delete_time')->
            where("ST_DISTANCE(POINT(lat, lng), POINT($lat,$lng)) IS NOT NULL") //距离不为空
//        ->where('distance_km', '<', get_sys_config('farthest_order_distance'))//距离小于配置的距离
            ->order('distance_km', 'asc')->
            paginate(100)->each(function ($item) {
                #可预约还是可服务
                $recentlyTime = getNowServiceTimeFunc($item->technician_id);

                $item->is_service = $recentlyTime['is_service'];
                $item->recentlyTime = $recentlyTime['day'] . ' ' . $recentlyTime['date'];

                #精确到小数点后两位
                $item->distance_km = (float) sprintf("%.2f", $item->distance_km);

                #拼接头像地址
                $item->avatar = IMAGE_URL . $item->avatar;
                #拼接身份证地址
                if (!empty($item->IDCard_imgs)) {
                    $item->IDCard_imgs = array_map(function ($v) {
                        return IMAGE_URL . $v;
                    }, explode(',', $item->IDCard_imgs ?? ""));
                }

                if (!empty($item->qualifications)) {
                    #资格证书地址
                    $item->qualifications = array_map(function ($v) {
                        return IMAGE_URL . $v;
                    }, explode(',', $item->qualifications));
                }
                if (!empty($item->health_imgs)) {
                    #拼接健康证书地址
                    $item->health_imgs = array_map(function ($v) {
                        return IMAGE_URL . $v;
                    }, explode(',', $item->health_imgs));
                }
                if (!empty($item->work_imgs)) {
                    #拼接工作形象照地址
                    $item->work_imgs = array_map(function ($v) {
                        return IMAGE_URL . $v;
                    }, explode(',', $item->work_imgs));
                }

            });
        $this->success('', [
            'list' => $ret->items(),
            'total' => $ret->total(),
        ]);
    }


    /**
     * 招募技师
     * @param int $type 1 保健师 2调理师
     * @param string $full_name 姓名
     * @param int $sex 性别 1男 2女
     * @param string|int $tel 电话
     * @param string|int $code 验证码
     * @param int $age 年龄
     * @param int $intention_city_id 意向合作城市
     * @param string $person_imgs 本人近期照
     * @param string $qualifications 资格证书
     * @param string $template_code 短信模板
     * @return void
     */
    public function recruit(): void
    {
        $post = $this->request->post();

        try {
            validate(\app\api\validate\Technician::class)->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息;
            $this->error($e->getError());
        }

        $this->model->where('tel', $post['tel'])->find() && $this->error('当前手机号已被注册！');
        $this->model->where('username', $post['tel'])->find() && $this->error('当前账号已存在,请前往app登录！');
        $type = $post['type'];
        $full_name = $post['full_name'];
        $sex = $post['sex'];
        $tel = $post['tel'];
        $code = $post['code'];
        $age = $post['age'];
        $intention_city_id = $post['intention_city_id'];
        $person_imgs = $post['person_imgs'];
        $qualifications = $post['qualifications'] ?? "";
        $template_code = $post['template_code'];
        if ($type == 2 && empty($qualifications)) {
            $this->error('资格证书不能为空!');
        }
        $IDCard_imgs = "";
        if (!empty($post['IDCard_imgs1']) || !empty($post['IDCard_imgs2'])) {
            $IDCard_imgs = trim($post['IDCard_imgs1'] . ',' . $post['IDCard_imgs2'], ',');
        }
        #验证短信验证码是否正确
        try {
            sms_check($tel, $code, $template_code);
            $salt = Random::build(8);
            $insert = [
                'username' => $tel,
                'password' => encrypt_password(123456, $salt),
                'salt' => $salt,
                'motto' => md5(123456),
                'type' => $type,
                'technician_name' => $full_name,
                'sex' => $sex,
                'tel' => $tel,
                'age' => $age,
                'area_id' => $intention_city_id,
                'intention_city_id' => $intention_city_id,
                'person_imgs' => $person_imgs,
                'qualifications' => $qualifications,
                'avatar' => $person_imgs,
                'work_imgs' => $person_imgs,
                'is_go_work' => 2,
                'create_time' => date('Y-m-d H:i:s', time()),
                'status' => 0,
                'health_imgs' => $post['health_imgs'] ?? "",
                'IDCard_imgs' => $IDCard_imgs,
                'business_license_img' => $post['business_license_img'] ?? "",
            ];
            Log::info("insert" . json_encode($insert));
            $this->model->create($insert);
        } catch (Throwable $e) {
            Log::error(' 招募申请失败' . $e->getMessage());
            $this->error("招募申请失败！");
        }
        $this->success('招募申请请成功！');
    }


}